package ru.jexp.rcp.supply.viewer;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeColumnViewerLabelProvider;
import org.eclipse.jface.viewers.TreeNode;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TreeColumn;

public class JExpTreeViewer extends TreeViewer {

	public JExpTreeViewer(Composite parent) {
		this(parent, null);
	}

	public JExpTreeViewer(Composite parent, JExpTreeLabelProvider provider) {
		super(parent, SWT.FULL_SELECTION);
		getTree().setHeaderVisible(true);
		getTree().setLinesVisible(true);
		setContentProvider(new JExpTreeNodeContentProvider());
		if (provider != null) {
			setJExpTreeLabelProvider(provider);
		}
	}

	public final void setJExpTreeLabelProvider(JExpTreeLabelProvider provider) {
		setLabelProvider(new TreeColumnViewerLabelProvider(provider));
		createColumn(provider);
	}

	public void setLayoutData(Object layoutData) {
		getTree().setLayoutData(layoutData);
	}

	public final void updateViewer(int action, TreeNode node) {
		switch (action) {
		case JExpTableViewer.ADD:
			addEelement(node);
			break;
		case JExpTableViewer.EDIT:
			updateElement(node);
			break;
		case JExpTableViewer.DELETE:
			removeElement(node);
			break;
		}
	}

	public final TreeNode getSelectionNode() {
		return (TreeNode) ((IStructuredSelection) getSelection())
				.getFirstElement();
	}
	
	@Override
	protected void inputChanged(Object input, Object oldInput) {
		super.inputChanged(input, oldInput);
		pack();
	}

	private void updateElement(TreeNode node) {
		update(node, null);
	}

	private void removeElement(TreeNode node) {
		getJExpContentProvider().deleteElement(node);
		remove(node);
	}

	private void addEelement(TreeNode node) {
		getJExpContentProvider().addElement(getSelectionNode(), node);
		add(getSelectionNode(), node);
	}

	private void pack() {
		for (TreeColumn column : getTree().getColumns()) {
			column.pack();
		}
	}

	private JExpTreeNodeContentProvider getJExpContentProvider() {
		return (JExpTreeNodeContentProvider) getContentProvider();
	}

	private void createColumn(JExpTreeLabelProvider provider) {
		for (int i = 0; i < provider.getColumnsSize(); i++) {
			TreeColumn treeColumn = new TreeColumn(getTree(), SWT.NONE);
			treeColumn.setWidth(200);
			treeColumn.setText(provider.getColumnName(i));
			treeColumn.setToolTipText(provider.getColumnName(i));
			treeColumn.setMoveable(i != 0);
			treeColumn.setResizable(true);
			treeColumn.pack();
		}
	}
}
